/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.live.multishop.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.LiveInterfaceType;
import com.yami.shop.bean.enums.LiveProdStatusType;
import com.yami.shop.bean.enums.LiveRoomStatusType;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.CharUtil;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.wx.WxInterfaceUtil;
import com.yami.shop.common.wx.bean.PageLiveRoomInfo;
import com.yami.shop.config.WxConfig;
import com.yami.shop.live.comment.constant.LiveConstant;
import com.yami.shop.live.comment.model.LiveLog;
import com.yami.shop.live.comment.model.LiveRoom;
import com.yami.shop.live.comment.model.LiveRoomBack;
import com.yami.shop.live.comment.param.LiveUsableNumParam;
import com.yami.shop.live.comment.service.LiveLogService;
import com.yami.shop.live.comment.service.LiveRoomBackService;
import com.yami.shop.live.comment.service.LiveRoomProdService;
import com.yami.shop.live.comment.service.LiveRoomService;
import com.yami.shop.security.multishop.util.SecurityUtils;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.Objects;


/**
 *
 *
 * @author lhd
 * @date 2020-08-05 08:53:17
 */
@RestController
@AllArgsConstructor
@RequestMapping("multishop/live/liveRoom" )
public class LiveRoomController {

    private final LiveRoomService liveRoomService;
    private final LiveLogService liveLogService;
    private final LiveRoomBackService liveRoomBackService;
    private final LiveRoomProdService liveRoomProdService;
    private final WxInterfaceUtil wxInterfaceUtil;
    private final WxConfig wxConfig;

    /**
     * 分页查询
     * @param page 分页对象
     * @param liveRoom
     * @return 分页数据
     */
    @GetMapping("/page" )
    public ResponseEntity<IPage<LiveRoom>> getLiveRoomPage(PageParam<LiveRoom> page, LiveRoom liveRoom) throws WxErrorException{
        IPage<LiveRoom> roomPage = liveRoomService.page(page, new LambdaQueryWrapper<LiveRoom>()
                .eq(LiveRoom::getShopId, SecurityUtils.getShopUser().getShopId()).orderByDesc(LiveRoom::getUpdateTime)
                .like(StrUtil.isNotBlank(liveRoom.getName()), LiveRoom::getName, liveRoom.getName())
                .like(StrUtil.isNotBlank(liveRoom.getAnchorName()), LiveRoom::getAnchorName, liveRoom.getAnchorName())
                .eq(Objects.nonNull(liveRoom.getLiveStatus()), LiveRoom::getLiveStatus, liveRoom.getLiveStatus())
                .ge(Objects.nonNull(liveRoom.getStartTime()), LiveRoom::getStartTime, liveRoom.getStartTime())
                .le(Objects.nonNull(liveRoom.getStartTime()), LiveRoom::getStartTime, liveRoom.getEndTime())
                .orderByDesc(LiveRoom::getStartTime)
        );
        if(CollectionUtils.isNotEmpty(roomPage.getRecords())) {
            for (LiveRoom liveRoomDb : roomPage.getRecords()) {
                LiveRoom.RoomToolsVO roomToolsVO = JSON.parseObject(liveRoomDb.getRoomTools(), LiveRoom.RoomToolsVO.class);
                liveRoomDb.setRoomToolsVo(roomToolsVO);
            }
        }
        return ResponseEntity.ok(roomPage);
    }


    /**
     * 通过id查询
     * @param id id
     * @return 单个数据
     */
    @GetMapping("/info/{id}" )
    public ResponseEntity<LiveRoom> getById(@PathVariable("id") Long id) {
        LiveRoom liveRoomDb = liveRoomService.getById(id);
        LiveRoom.RoomToolsVO roomToolsVO = JSON.parseObject(liveRoomDb.getRoomTools(), LiveRoom.RoomToolsVO.class);
        liveRoomDb.setRoomToolsVo(roomToolsVO);
        return ResponseEntity.ok(liveRoomDb);
    }

    /**
     * 通过id查询
     * @param id id
     * @return 单个数据
     */
    @GetMapping("/getPlayBack/{id}" )
    public ResponseEntity<LiveRoomBack> getPlayBackByRoomId(@PathVariable("id") Long id) {
        return ResponseEntity.ok(liveRoomBackService.getOne(new LambdaQueryWrapper<LiveRoomBack>().eq(LiveRoomBack::getRoomId,id)));
    }

    /**
     * 新增
     * @param liveRoom 直播间信息
     * @return 是否新增成功
     */
    @SysLog("新增" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('live:liveRoom:save')")
    public ResponseEntity<Boolean> save(@RequestBody @Valid LiveRoom liveRoom) throws WxErrorException {
        if(CharUtil.length(liveRoom.getName()) < LiveConstant.ROOM_NAME_MIN_LENGTH || CharUtil.length(liveRoom.getName()) > LiveConstant.ROOM_NAME_MAX_LENGTH){
            // 直播间名称长度非法,最短3个汉字，最长17个汉字！
            throw new YamiShopBindException("yami.live.room.name.check");
        }
        if(CharUtil.length(liveRoom.getAnchorName()) < LiveConstant.USER_NAME_MIN_LENGTH || CharUtil.length(liveRoom.getAnchorName()) > LiveConstant.USER_NAME_MAX_LENGTH){
            // 主播昵称长度非法，最短2个汉字，最长15个汉字
            throw new YamiShopBindException("yami.live.room.name.check2");
        }
        liveRoom.setShopId(SecurityUtils.getShopUser().getShopId());
        liveRoom.setUpdateTime(new Date());
        liveRoom.setApplyTime(new Date());
        liveRoom.setLiveStatus(LiveRoomStatusType.NO_START.value());
        liveRoomService.saveLiveRoom(liveRoom);
        return ResponseEntity.ok().build();
    }

    /**
     * 添加直播间商品
     * @param liveRoom 直播间商品
     * @return 是否添加成功
     */
    @PostMapping("/addLiveRoomProd")
    public ResponseEntity<Boolean> addLiveRoomProd(@RequestBody @Valid LiveRoom liveRoom) throws WxErrorException{
        liveRoom.setShopId(SecurityUtils.getShopUser().getShopId());
        liveRoomProdService.saveBatchAndRoomId(liveRoom);
        return ResponseEntity.ok().build();
    }


    /**
     * 查询商家今日剩余可用添加直播间次数
     */
    @GetMapping("/getAddRoomNum" )
    public ResponseEntity<LiveUsableNumParam> getAddRoomNum() {
        return ResponseEntity.ok(liveLogService.getLiveNum(SecurityUtils.getShopUser().getShopId(),LiveInterfaceType.CREATE_ROOM));
    }


}
